import Layout from '../views/layout/Layout'

export function parse_menu(data) {
  let result = getPage(data);
  result.push({path: '*', redirect: '/404', hidden: true})
  return result;
}

/**
 * 构建菜单
 *
 * @param allList
 * @returns {[]}
 */
function getPage(allList) {
  let tempArr = allList;

  // 构建的菜单数据
  let menuList = [];
  // 获取所有的父级菜单
  allList.forEach((menu, index) => {
    // 一级菜单parentId == 0
    if (menu.parentId === 0) {
      // 判断该菜单是目录还是菜单 0=目录，1=菜单
      let temp;
      if (menu.type === 1) {
        temp = {
          menuId: menu.pageId,
          parentId: menu.parentId,
          path: '',
          component: Layout,
          redirect: '/' + menu.url,
          children: [
            {
              item: 'one',
              path:  menu.url,
              name: menu.name,
              component: resolve => require([`@/views/${menu.url}/index.vue`], resolve),
              meta: {title: menu.name, icon: menu.icon ? menu.icon : 'form'}
            }
          ]
        };
      } else {
        temp = {
          menuId: menu.pageId,
          parentId: menu.parentId,
          path: '/' + menu.url,
          name: menu.name,
          component: Layout,
          redirect: '/dashboard',
          meta: {title: menu.name, icon: menu.icon ? menu.icon : 'form'},
          children: []
        };
      }
      menuList.push(temp);
    }
  });

  menuList.forEach((menu, index) => {
    menu.children = menu.children.concat(getChild(menu.menuId, allList))
  })

  return menuList;
}

/**
 *  构建子菜单数据
 *
 * @param menuId
 * @param menuArr
 * @returns {[]}
 */
function getChild(menuId, allList) {
  let chileArr = [];
  allList.forEach((menu, index) => {

    // 遍历所有节点，将父菜单id与传过来的id比较
    if (menu.parentId !== 0) {
      if (menu.parentId === menuId) {
        let temp;
        if (menu.type === 1) {
          temp = {
            menuId: menu.pageId,
            parentId: menu.parentId,
            path: menu.url,
            name: menu.name,
            component: resolve => require([`@/views/${menu.url}/index.vue`], resolve),
            meta: {title: menu.name, icon: menu.icon ? menu.icon : 'form'}
          }
        }
        chileArr.push(temp);
      }
    }
  })
  return chileArr;
}

